<?php
if($_SESSION['brg_kluar']!=1){
	echo "Akses tidak diizinkan";
	exit();
}
$act = filter($_GET['act']);
$field = filter($_GET['field']);
$q = filter($_GET['q']);

if(empty($act)){	
?>		
					<!-- box / title -->
					<div class="title">
						<h5>Data Barang keluar</h5>								
						<div class="search global-nav">
					  <form method="GET" class="form-search js-search-form" action="index.php?pages=brg_kluar" id="global-nav-search" style="width:350px">
								<input type="hidden" name="pages" value="brg_kluar">
								<select name="field" id="birthday_month" aria-label="Month" class="" >
									<option value="" <?php echo ($field=="")?"selected":"";?>>Cari Berdasarkan:</option>
									<option value="tgl_jual" <?php echo ($field=="tgl_jual")?"selected":"";?>>Tgl terjual</option>
								  <option value="nota" <?php echo ($field=="nota")?"selected":"";?>>Nota</option>	
				</select>

				            	<label class="visuallyhidden" for="search-query">Search query</label>
				            	<input class="search-input" type="text" id="search-query" placeholder="Search" name="q" value="<?php echo $q;?>">
				            	<span class="search-icon js-search-action">
				              		<button type="submit" class="icon nav-search" tabindex="-1">
				              			<span class="visuallyhidden">Search</span>
				              		</button>
				            	</span>
				            	<input disabled="disabled" class="search-input search-hinting-input" type="text" id="search-query-hint" autocomplete="off" spellcheck="false">				              					              
							</form>
						</div>
					</div>
					<!-- end box / title -->
					<div class="table">										
						<table>
							<thead>
								<tr>
									<th class="selected"><input type="checkbox" class="checkall" /></th>
									<th class="action">No.</th>
                                    <th>Nota</th>
									<th class="left">Customer</th>
									<th>Tgl Jual</th>
									<th>Sales</th>
                                    <th class="action" colspan="2"><a href="?pages=brg_kluar&act=edit" class="icon-plus-sign" title="Tambah Data Baru"></a></th>									
								</tr>
							</thead>
							<tbody>
							<?php			

							$q2=$q;
							if($field=='status'){
								$q2 = (strtolower($q)=='aktif')?'1':'0';
							}
							
							$addQuery='';
							if(!empty($field))
								$addQuery .= " WHERE $field LIKE '%$q2%' ";

							$batas=10;
							$pg=(int) $_GET['pg'];
							if(empty($pg))
							{
								$posisi=0;
								$pg=1;
							}
							else
							{
								$posisi = ($pg-1) * $batas;
							}
							$sqlSup1 = mysql_query("SELECT * FROM tb_penjualan $addQuery ORDER BY id_penjualan DESC LIMIT $posisi, $batas");
							
							$no=$posisi+1;
							while($dataSup = mysql_fetch_array($sqlSup1)){								

								$status = ($dataSup['status']==1)? "Aktif":"Non Aktif";
							?>
								<tr>
									<td class="selected"><input type="checkbox" /></td>
									<td class="center"><?php echo $no;?></td>
                                    <td><?php echo $dataSup['nota'];?></td>
                                     <?php 
										  $sql=mysql_query("select * from tb_customer where id_customer='$dataSup[id_customer]'");
										  $sql2=mysql_fetch_array($sql);
									?>
									<td><?php echo $sql2['nama'];?></td>
									<td><?php echo $dataSup['tgl_jual'];?></td>
									<!--<td><?php echo $dataSup['nota'];?></td>-->
                                    <?php 
										  $sql=mysql_query("select * from tb_sales where id_sales='$dataSup[id_sales]'");
										  $sql2=mysql_fetch_array($sql);
									?>
                                    <td><?php echo $sql2['nama'];?></td>
                                    
                                    <td class="action"><a href="?pages=brg_kluar&act=edit&id=<?php echo $dataSup['id_penjualan'];?>" class="icon-edit" title="Ubah Data"></a></td>
									<td class="action">
										<a href="#" title="Hapus Data" onClick="if(confirm('Anda akan menghapus data ini?')) window.location='?pages=brg_kluar&act=del&id=<?php echo $dataSup['id_penjualan'];?>';" class="icon-trash"></a>
									</td>								
								</tr>
							<?php	
								$no++;				
							}

							$sqlSup2 = mysql_query("SELECT * FROM tb_penjualan $addQuery ORDER BY id_penjualan DESC");
							$jumlahData = mysql_num_rows($sqlSup2);

							$file="?pages=brg_kluar&field=$field&q=$q";
							$jmlhalaman=ceil($jumlahData/$batas);
	
							?>															
							</tbody>
						</table>
						<!-- pagination -->
					  <div class="pagination pagination-left">
							<div class="results">
								<span><?php echo "Showing Results ".($posisi+1)."-".($no-1)." of $jumlahData";?></span>
							</div>
							<ul class="pager">
								<?php
								//link ke halaman sebelumnya (previous)
								if($pg > 1){
									$previous=$pg-1;
									echo "<li><a href=$file&pg=1>&laquo; First</a></li>
									<li><a href=$file&pg=$previous>&laquo; Prev</a></li> ";
								}else{ 
									echo "<li class='disabled'>&laquo; First</li>
									<li class='disabled'>&laquo; Prev</li> ";
								}
								?>

								<?php
								//Link untuk Angka
								$angka=($pg > 3 ? " <li class='separator'>...</li> " : " ");
								for($i=$pg-2;$i<$pg;$i++)
								{
								  if ($i < 1) 
								      continue;
								  $angka .= "<li><a href='$file&pg=$i'>$i</a></li> ";
								}

								$angka .= " <li class='current'>$pg</li>";
								for($i=$pg+1;$i<($pg+3);$i++)
								{
								  if ($i > $jmlhalaman) 
								      break;
								  $angka .= "<li><a href='$file&pg=$i'>$i</a></li> ";
								}

								$angka .= ($pg+2<$jmlhalaman ? " <li class='separator'>...</li> <li><a href='$file&pg=$jmlhalaman'>$jmlhalaman</a></li>" : " ");

								echo "$angka";
								?>
								

								<?php
								//link kehalaman berikutnya (Next)
								if($pg < $jmlhalaman)
								{
									$next=$pg+1;
									echo "<li><a href='$file&pg=$next'>Next &raquo;</a></li>
									<li><a href='$file&pg=$jmlhalaman'>Last &raquo;</a></li>";
								}
								else
								{ 
									echo "<li class='disabled'>Next &raquo;</li>
									<li class='disabled'>Last &raquo;</li> ";
								}		
								?>													
							</ul>
						</div>

						<!-- end pagination -->
						<!-- table action -->
						
						<!-- end table action -->						
					</div>

<?php
}elseif ($act=='edit') {

	$id_penjualan = (int) filter($_GET['id']);

	$sqlSup = mysql_query("SELECT * FROM tb_penjualan WHERE id_penjualan=$id_penjualan");
	$dataSup = mysql_fetch_array($sqlSup);
	$type = ($dataSup['type']==RTS)? "RTS":"RTU";

	if(!empty($id_penjualan)){
		?>
		<!-- box / title -->
		<div class="title">
			<h5>Ubah Data Barang keluar</h5>														
		</div>
		<!-- end box / title -->
		<?php
	}else{
		?>
		<!-- box / title -->
		<div class="title">
			<h5>Tambah Barang keluar</h5>														
		</div>
		<!-- end box / title -->
		<?php
	}
?>

	<div class="table">
		<form method="POST" action="?pages=brg_kluar&act=update">
		<input type="hidden" name="id_penjualan" value="<?php echo $dataSup['id_penjualan'];?>">
		<table style="width:auto;display:inline">
		   	<tbody>
		   		<tr>
					<td><label>Nota</label></td>
					<td>:</td>
					<td><input type="text" value="<?php echo $dataSup['nota'];?>" size="60" name="nota" id="nota" placeholder="Nota" required></td>
			   	</tr>
			   	<tr>
					<td><label>Customer</label></td>
					<td>:</td>
					<td><select class="select" style="width: 210px;" name="id_customer" id="id_customer"  data-placeholder="Pilih Customer" required="required">
					  <option value=""></option>
					  <?php
                            $selectJns = mysql_query("SELECT * FROM tb_customer");
                            while($dataJns = mysql_fetch_array($selectJns)){
							 	if($dataSup['id_customer']==$dataJns['id_customer']){
						  			$selected = " selected ";
							  	}else{
							  		$selected = "";
							  	}
                      			?>
					  <option <?php echo $selected;?> value="<?php echo "$dataJns[id_customer]";?>"><?php echo "$dataJns[nama]=>$dataJns[perusahaan]";?></option>
					  <?php
                            }
                      		?>
				    </select></td>
			   	</tr>
			   	<tr>
					<td><label>Tgl Jual</label></td>
					<td>:</td>
					<td><input type="text"  value="<?php echo $dataSup['tgl_jual'];?>" size="30" name="tgl_jual" id="tgl_jual" placeholder="Tgl Jual" required/></td>
				</tr>
				<tr>
					<td><label>Sales</label></td>
					<td>:</td>
					<td>
						<select class="select" style="width: 210px;" name="id_sales" id="id_sales" data-placeholder="Pilih Sales" required>
                      		<option value=""></option>
                      		<?php
                            $selectJns = mysql_query("SELECT * FROM tb_sales");
                            while($dataJns = mysql_fetch_array($selectJns)){
							 	if($dataSup['id_sales']==$dataJns['id_sales']){
						  			$selected = " selected ";
							  	}else{
							  		$selected = "";
							  	}
                      			?>
                      			<option <?php echo $selected;?> value="<?php echo "$dataJns[id_sales]";?>"><?php echo "$dataJns[nama]";?></option>
                      		<?php
                            }
                      		?>
                        </select>
                    </td>

				</tr>			   	
			 	<tr>
			 		<td>&nbsp;</td>
			 		<td>&nbsp;</td>
			 		<td>
			 			<input type="hidden" value="" size="15" name="id">
						<input type="submit" value="Simpan" name="submit" class="btn btn-primary">
						<input type="Reset" value="Reset" class="btn">
			 		</td>
		   		</tr>
		 	</tbody>
		</table>
		<table style="width:auto;display:inline;margin-left:20px">
	   	  <tbody>
		   		<tr>
					<th class="action"><button class="icon-plus-sign" id="add_formula" title="Tambah Data Baru"></button></th>
					<th><label><b>Detail Barang keluar</b></label></th>					
			   	</tr>
			   	<tr>
			   		<td colspan="2">
			   			<?php			   			
			   			$sqlDetail = mysql_query("SELECT * FROM tb_detail_penjualan WHERE id_penjualan='".$dataSup[id_penjualan]."'");
			   			$ono = mysql_num_rows($sqlDetail);
			   			if(!$ono){
			   				?>
			   				<div id="detail_formula" class="tabelDetail">
					   			<table style="width:600px;">
									<tbody>
                                    <tr>
											<td colspan="4">===============================================================</td>
									  </tr>
								   		<tr>
											<td>Jenis Barang</td>
											<td><select class="chzn-select" style="width: 210px;" name="id_jns_brg[]" id="id_jns_brg"  data-placeholder="Pilih Jenis Barang" required="required">
											  <option value=""></option>
							<?php
								$selectJns = mysql_query("SELECT * FROM  tb_jns_barang");
								while($dataJns = mysql_fetch_array($selectJns)){
								if($dataSup['id_jns_brg']==$dataJns['id_jns_brg']){
								$selected = " selected ";
								}else{
								$selected = "";
								}
								?>
								<option <?php echo $selected;?> value="<?php echo "$dataJns[id_jns_brg]";?>"><?php echo "$dataJns[kode_brg]=>$dataJns[nama_brg]";?></option>
                            <?php
                            }
                            ?>
										    </select></td>
											<td>Jumlah Stok Rts</td>	
											<td><input type="text" size="30" name="jumlah_rts[]" id="jumlah_rts[]" placeholder="Jumlah Bahan Baku" required />
                                            
                                            </td>															
											<td rowspan="9" style="vertical-align:middle"><button class="icon-minus-sign" title="Hapus Data" onClick="deleteAddress(this);return false" ></button></td>
									   	</tr>
									   	<tr>
											<td>Jumlah </td>
											<td><input type="text" size="30" name="jumlah[]" id="jumlah[]" placeholder="Jumlah" required /></td>
											<td>Jumlah Stok Perbaikan</td>				
											<td><input type="text" size="30" name="jumlah_reject[]" id="jumlah_reject[]" placeholder="Jumlah Bahan Baku" required /></td>
									   	</tr>
                                        <tr>
											<td>Jumlah Cad</td>
											<td><input type="text" size="30" name="jumlah_cad[]" id="jumlah_cad[]" placeholder="Jumlah Bahan Baku" required /></td>
											<td>Satuan</td>				
											<td><input type="text" value="Karton" size="30" name="satuan[]" id="satuan"  readonly="true" /></td>
									   	</tr>
									   <tr>
											<td colspan="4" align="center"><label><b>Input Reject</b></label></td>
									  </tr>
                                        <tr>
											<td>Jumlah Rusak Dus</td>
											<td><input type="text" size="30" name="jumlah_rusak_dus[]" id="jumlah_rusak_dus" placeholder="Jumlah Bahan Baku" /></td>
											<td>Jumlah Cup Ok</td>				
											<td><input type="text" size="30" name="jumlah_cup_ok[]" id="jumlah_cup_ok[]" placeholder="Jumlah Bahan Baku" /></td>
									   	</tr>
                                        <tr>
											<td>satuan Rusak Dus</td>
											<td><input type="text" value="Karton" size="30" name="satuan_rusak_dus[]" id="satuan"  readonly="true" required="required"/></td>
											<td>Jumlah Kembali</td>				
											<td><input type="text" size="30" name="jumlah_kembali[]" id="jumlah_kembali" placeholder="Jumlah Bahan Baku" /></td>
									   	</tr>
                                        <tr>
											<td>Jumlah Rusak Cup</td>
											<td><input type="text" size="30" name="jumlah_rusak_cup[]" id="jumlah_rusak_cup" placeholder="Jumlah Bahan Baku" /></td>
											<td>Satuan Kembali</td>				
											<td><input type="text" value="Karton" size="30" name="satuan_kembali[]" id="satuan_kembali"  readonly="true" required="required"/></td>
									   	</tr>
                                         <tr>
											<td>satuan Rusak Cup</td>
											<td><input type="text" value="Cup" size="30" name="satuan_rusak_cup[]" id="satuan"  readonly="true" required="required"/></td>
											<td>&nbsp;</td>				
											<td>&nbsp;</td>
									   	</tr>
									</tbody>
								</table>

</div>
			   				<?php
			   			}else{
			   				$y==0;
			   				while ($dataDetail = mysql_fetch_array($sqlDetail)) {
			   					$id_jns_brg=$dataDetail['id_jns_brg'];
								$y++;
			   					?>
			   					<div id="detail_formula" class="tabelDetail">
			   					  <table style="width:600px;">
									<tbody>
                                    <tr>
											<td colspan="4">===============================================================</td>
									  </tr>
								   		<tr>
											<td>Jenis Barang</td>
											<td><input type="hidden" name="id_detail_penjualan[]" value="<?php echo $dataDetail['id_detail_penjualan'];?>">
                                            
<select name="id_jns_brg[]"  style="width:212px" id="chzn-selectx<?php echo $y;?>">
<?php
$sqlBB = mysql_query("SELECT * FROM tb_jns_barang GROUP BY id_jns_brg");
while ($dataBB = mysql_fetch_array($sqlBB)) {
    if($id_jns_brg==$dataBB['id_jns_brg']){
        $selected = " selected ";
    }else{
        $selected = " ";
    }

    echo "<option value='".$dataBB['id_jns_brg']."' $selected>".$dataBB['kode_brg']."=>".$dataBB['nama_brg']."</option>";
}
?>
</select>
                                            
                                            </td>
											<td>Jumlah Stok Rts</td>	
											<td><input type="text" size="30" value="<?php echo $dataDetail['jumlah_rts'];?>" name="jumlah_rts[]" id="jumlah" placeholder="Jumlah RTS"  />
                                            <input type="hidden" size="30" value="<?php echo $dataDetail['jumlah_rts'];?>" name="jumlah_rtsx[]"   /></td>															
											<td rowspan="9" style="vertical-align:middle"><a class="icon-minus-sign" title="Hapus Data" onClick="if(confirm('Anda akan menghapus data ini?')) window.location='?pages=brg_kluar&act=delDetail&id=<?php echo $dataDetail['id_detail_penjualan'];?>&id2=<?php echo $dataSup['id_penjualan'];?>';" ></a></td>
									   	</tr>
									   	<tr>
											<td>Jumlah </td>
											<td><input type="text" size="30" value="<?php echo $dataDetail['jumlah'];?>" name="jumlah[]" id="jumlah" placeholder="Jumlah" required /></td>
											<td>Jumlah Stok Perbaikan</td>				
											<td><input type="text" size="30"
value="<?php echo $dataDetail['jumlah_reject'];?>" name="jumlah_reject[]" id="jumlah_rejectx[]" placeholder="Jumlah Reject" required  />

<input type="hidden" size="30"
value="<?php echo $dataDetail['jumlah_reject'];?>" name="jumlah_rejectx[]"    />
</td>
									   	</tr>
                                        <tr>
											<td>Jumlah Cad</td>
											<td><input type="text" size="30"
value="<?php echo $dataDetail['jumlah_cad'];?>" name="jumlah_cad[]" id="jumlah_cad[]" placeholder="Jumlah Reject" required/></td>
											<td>Satuan</td>				
											<td><input type="text" value="Karton" size="30" name="satuan[]" id="satuan"  readonly="true" required="required"/></td>
									   	</tr>
									   <tr>
											<td colspan="4" align="center"><label><b>Input Reject</b></label></td>
									  </tr>
                                        <tr>
											<td>Jumlah Rusak Dus</td>
											<td><input type="text" size="30"
value="<?php echo $dataDetail['jumlah_rusak_dus'];?>" name="jumlah_rusak_dus[]" id="jumlah_rusak_dus" placeholder="Jumlah rusak dus" /></td>
											<td>Jumlah Cup Ok</td>				
											<td><input type="text" size="30"
value="<?php echo $dataDetail['jumlah_cup_ok'];?>" name="jumlah_cup_ok[]" id="jumlah_cup_ok" placeholder="Jumlah cup ok" />

<input type="hidden" size="30"
value="<?php echo $dataDetail['jumlah_cup_ok'];?>" name="jumlah_cup_okx[]" /></td>
									   	</tr>
                                        <tr>
											<td>satuan Rusak Dus</td>
											<td><input type="text" value="Karton" size="30" name="satuan_rusak_dus[]" id="satuan_rusak_dus"  readonly="true" /></td>
											<td>Jumlah Kembali</td>				
											<td><input type="text" size="30"
value="<?php echo $dataDetail['jumlah_kembali'];?>" name="jumlah_kembali[]" id="jumlah_kembali" placeholder="Jumlah kembali" />

<input type="hidden" size="30"
value="<?php echo $dataDetail['jumlah_kembali'];?>" name="jumlah_kembalix[]"  /></td>
									   	</tr>
                                        <tr>
											<td>Jumlah Rusak Cup</td>
											<td><input type="text" size="30"
value="<?php echo $dataDetail['jumlah_rusak_cup'];?>" name="jumlah_rusak_cup[]" id="jumlah_rusak_cup" placeholder="Jumlah rusak cup" /></td>
											<td>Satuan Kembali</td>				
											<td><input type="text" value="Karton" size="30" name="satuan_kembali[]" id="satuan_kembali"  readonly="true" /></td>
									   	</tr>
                                         <tr>
											<td>satuan Rusak Cup</td>
											<td><input type="text" value="Cup" size="30" name="satuan_rusak_cup[]" id="satuan_rusak_cup"  readonly="true" /></td>
											<td>&nbsp;</td>				
											<td>&nbsp;</td>
									   	</tr>
									</tbody>
								</table>
  </div>
								<script type="text/javascript">
								$(document).ready(function () {
																		 
									$("#chzn-selectx<?php echo $y; ?>").chosen();   								
								});
								</script>
			   					<?php
			   				}
			   			}
			   			
			   			?>			   			
			   		</td>
			   	</tr>
			</tbody>
		</table>
		
		</form>
	</div>
<?php
}elseif ($act=='update') {
	# code...
	$id_penjualan = (int) $_POST['id_penjualan'];
	$nota = $_POST['nota'];
	$id_customer = $_POST['id_customer'];
	$tgl_jual = $_POST['tgl_jual'];
	$id_sales = $_POST['id_sales'];

	$jmlData = count($_POST['id_jns_brg']);

	$id_detail_penjualan	=$_POST['id_detail_penjualan'];
	$id_jns_brg				=$_POST['id_jns_brg'];
	$jumlah_rts				=$_POST['jumlah_rts'];
	$jumlah_reject			=$_POST['jumlah_reject'];
	$jumlah 				=$_POST['jumlah'];
	$jumlah_cad				=$_POST['jumlah_cad'];
	$satuan 				=$_POST['satuan'];
	$jumlah_rusak_dus 		=$_POST['jumlah_rusak_dus'];
	$jumlah_cup_ok 			=$_POST['jumlah_cup_ok'];
	$satuan_rusak_dus		=$_POST['satuan_rusak_dus'];
	$jumlah_kembali 		=$_POST['jumlah_kembali'];
	$jumlah_rusak_cup 		=$_POST['jumlah_rusak_cup'];
	$satuan_kembali			=$_POST['satuan_kembali'];
	$satuan_rusak_cup		=$_POST['satuan_rusak_cup'];

	$jumlah_rtsx = $_POST['jumlah_rtsx'];
	$jumlah_rejectx = $_POST['jumlah_rejectx'];
	$jumlah_cup_okx = $_POST['jumlah_cup_okx'];
	$jumlah_kembalix= $_POST['jumlah_kembalix'];
	
	if(!empty($id_penjualan)){
		$update = mysql_query("UPDATE tb_penjualan SET id_customer='$id_customer', tgl_jual='$tgl_jual', nota='$nota', id_sales='$id_sales' WHERE id_penjualan='$id_penjualan'");

		if($update){
			for ($i=0; $i < $jmlData; $i++) { 

				$update_temp_rts=mysql_query("SELECT * from tb_temp_rts where id_jns_brg='$id_jns_brg[$i]'");
				$cek_rts=mysql_fetch_array($update_temp_rts);
				 $temp2=$cek_rts["stock_rts"];
				 $temp3=$cek_rts["stock_perbaikan"];
				 $temp4=$cek_rts["stock_cup_sehat"];

				$total1[$i]= $jumlah[$i] + $jumlah_cad[$i];
				$total2[$i]= $jumlah_rts[$i] + $jumlah_reject[$i];

				$total_temp[$i]=($temp2 + $jumlah_rtsx[$i])- $jumlah_rts[$i];
				$total_temp2[$i]=($temp3 + $jumlah_rejectx[$i])- $jumlah_reject[$i];
				$total_temp3[$i]=($temp4 - $jumlah_cup_okx[$i])+ $jumlah_cup_ok[$i];

				$total_rts[$i]=$temp2 - $jumlah_rts[$i];
				$total_perbaikan[$i]= $temp3 - $jumlah_reject[$i];
				$total_cup_ok[$i]=$temp4 + $jumlah_cup_ok[$i];

				$rts_kembali[$i]=($temp2 - $jumlah_kembalix[$i])+ $jumlah_kembali[$i];

				if($total1[$i] != $total2[$i]){
					sukses('Data RTS & Reject Anda tidak sama dengan Jumlah Barang yang di jual', "?pages=brg_kluar&act=edit&id=$id_penjualan");
				}else if($jumlah_rts[$i] > $temp2){
					sukses('Data RTS melebihi stok di Database', "?pages=brg_kluar&act=edit&id=$id_penjualan");
				}else if($jumlah_reject[$i] > $temp3){
					sukses('Data Perbaikan melebihi stok di Database', "?pages=brg_kluar&act=edit&id=$id_penjualan");
				}else{

	
					if(!empty($id_detail_penjualan[$i])){
						$updateDetail = mysql_query("UPDATE tb_detail_penjualan SET  jumlah_cad='$jumlah_cad[$i]', 
							jumlah='$jumlah[$i]', jumlah_rts='$jumlah_rts[$i]', jumlah_reject='$jumlah_reject[$i]', satuan='$satuan[$i]',
							id_jns_brg='$id_jns_brg[$i]', jumlah_cup_ok='$jumlah_cup_ok[$i]', jumlah_rusak_dus='$jumlah_rusak_dus[$i]', 
							satuan_rusak_dus='$satuan_rusak_dus[$i]', jumlah_rusak_cup='$jumlah_rusak_cup[$i]', satuan_rusak_cup='$satuan_rusak_cup[$i]'
							,jumlah_kembali='$jumlah_kembali[$i]', satuan_kembali='$satuan_kembali[$i]'  WHERE id_detail_penjualan='$id_detail_penjualan[$i]' ");


							$updatex=mysql_query("UPDATE tb_temp_rts SET stock_rts='$total_temp[$i]', stock_perbaikan='$total_temp2[$i]', stock_cup_sehat='$total_temp3[$i]' WHERE id_jns_brg='$id_jns_brg[$i]'");

							
							$insertx=mysql_query("INSERT INTO tb_rts VALUES(NULL,NULL,'$jumlah_kembali[$i]','$satuan_kembali[$i]',NULL,NULL,'1','$id_jns_brg[$i]','$id_detail_penjualan[$i]')");

					if($insertx){

						$update_temp2=mysql_query("UPDATE tb_temp_rts SET stock_rts='$rts_kembali[$i]' WHERE id_jns_brg='$id_jns_brg[$i]'");
					}

					}else{
						if(!empty($id_jns_brg[$i]) && !empty($jumlah[$i]) && ($jumlah_cad[$i] >= 0)  && ($jumlah_rts[$i] >= 0) && ($jumlah_reject[$i] >= 0) && !empty($satuan[$i])){
						
							$insertDetail = mysql_query("INSERT INTO tb_detail_penjualan VALUES(NULL, '$id_penjualan', '$jumlah_cad[$i]', '$jumlah[$i]' 
								, '$jumlah_rts[$i]', '$jumlah_reject[$i]', '$satuan[$i]', '$id_jns_brg[$i]', '$jumlah_cup_ok[$i]', '$jumlah_rusak_dus[$i]'
								, '$satuan_rusak_dus[$i]', '$jumlah_rusak_cup[$i]', '$satuan_rusak_cup[$i]', '$jumlah_kembali[$i]', '$satuan_kembali[$i]','1')");

						}
						if ($insertDetail){
							$updatex2=mysql_query("UPDATE tb_temp_rts SET stock_rts='$total_rts[$i]', stock_perbaikan='$total_perbaikan[$i]',stock_cup_sehat='$total_cup_ok[$i]' WHERE id_jns_brg='$id_jns_brg[$i]'");

							
							$insertx2=mysql_query("INSERT INTO tb_rts VALUES(NULL,NULL,'$jumlah_kembali[$i]','$satuan_kembali[$i]',NULL,NULL,'1','$id_jns_brg[$i]','$id_detail_penjualan[$i]')");
							if($insertx2){

								$update_tempx2=mysql_query("UPDATE tb_temp_rts SET stock_rts='$rts_kembali[$i]' WHERE id_jns_brg='$id_jns_brg[$i]'");
							}
						}
						
					}					
				
				}

			}
		}

		if(($updateDetail && $updatex && $insertx)|| ($insertDetail && $updatex2 && $insertx2))
			sukses('Data berhasil disimpan', "?pages=brg_kluar&act=edit&id=$id_penjualan");
	}else{
		$insert = mysql_query("INSERT INTO tb_penjualan VALUES(NULL, '$id_customer', '$tgl_jual', '$nota', '$id_sales')");

		if($insert){


			$sqlFormula = mysql_query("SELECT id_penjualan FROM tb_penjualan ORDER BY id_penjualan DESC LIMIT 1");
			$latestFormula = mysql_fetch_array($sqlFormula);
			$id_penjualan = $latestFormula['id_penjualan'];

			for ($i=0; $i < $jmlData; $i++) { 

				$update_temp_rts=mysql_query("SELECT * from tb_temp_rts where id_jns_brg='$id_jns_brg[$i]'");
				$cek_rts=mysql_fetch_array($update_temp_rts);
				$temp2=$cek_rts["stock_rts"];
				$temp3=$cek_rts["stock_perbaikan"];

				$total1[$i]= $jumlah[$i] + $jumlah_cad[$i];
				$total2[$i]= $jumlah_rts[$i] + $jumlah_reject[$i];

				$total_rts[$i]=$temp2 - $jumlah_rts[$i];
				$total_perbaikan[$i]= $temp3 - $jumlah_reject[$i];


				if($total1[$i] != $total2[$i]){
					sukses('Data RTS & Reject Anda tidak sama dengan Jumlah Barang yang di jual', "?pages=brg_kluar&act=edit&id=$id_penjualan");
				}else if($jumlah_rts[$i] > $temp2){
					sukses('Data RTS melebihi stok di Database', "?pages=brg_kluar&act=edit&id=$id_penjualan");
				}else if($jumlah_reject[$i] > $temp3){
					sukses('Data Perbaikan melebihi stok di Database', "?pages=brg_kluar&act=edit&id=$id_penjualan");
				}else {
					if(!empty($id_jns_brg[$i]) && !empty($jumlah[$i]) && ($jumlah_cad[$i] >= 0)  && ($jumlah_rts[$i] >= 0) && ($jumlah_reject[$i] >= 0) && !empty($satuan[$i])){
						$insertDetail = mysql_query("INSERT INTO tb_detail_penjualan VALUES(NULL, '$id_penjualan', '$jumlah_cad[$i]', '$jumlah[$i]' 
							, '$jumlah_rts[$i]', '$jumlah_reject[$i]', '$satuan[$i]', '$id_jns_brg[$i]', '', '', '', '', '', '', '','1')");
					


					}
					if ($insertDetail){
							$updatex=mysql_query("UPDATE tb_temp_rts SET stock_rts='$total_rts[$i]', stock_perbaikan='$total_perbaikan[$i]' WHERE id_jns_brg='$id_jns_brg[$i]'");
					}
				}
			}
		}

		if($insertDetail && $updatex)
			sukses('Data berhasil disimpan', '?pages=brg_kluar');
	}
	
}elseif ($act=='del') {
	# code...
	$id_penjualan = (int) filter($_GET['id']);

	$delete = mysql_query("DELETE FROM tb_penjualan WHERE id_penjualan=$id_penjualan");

	$delete2 = mysql_query("DELETE FROM tb_detail_penjualan WHERE id_penjualan=$id_penjualan");

	if($delete && $delete2)
		sukses('Data berhasil dihapus', '?pages=brg_kluar');
}elseif ($act=='delDetail') {
	# code...
	$id_penjualan = (int) filter($_GET['id2']);
	$id_detail_penjualan = (int) filter($_GET['id']);

	$delete = mysql_query("DELETE FROM tb_detail_penjualan WHERE id_detail_penjualan=$id_detail_penjualan");

	if($delete)
		sukses('Data berhasil dihapus', "?pages=brg_kluar&act=edit&id=$id_penjualan");

}
?>					

<link rel="stylesheet" href="css/chosen.css" />
<script src="js/chosen.jquery.js" type="text/javascript"></script>
<script type="text/javascript">
			function deleteAddress(e) {
				if($(e).parents(".tabelDetail").is('#detail_formula')){
					alert('Sisain satu ya..:p');
				}else{
					$(e).parents(".tabelDetail").remove();
				}
				
			}

			$(document).ready(function () {
				style_path = "css/colors";
				$('.dropdown-toggle').dropdown();
				//$("#date-picker").datepicker();

				//$("#box-tabs, #box-left-tabs").tabs();

				 $('.dropdown input, .dropdown label, .dropdown-menu').click(function(e) {
				    e.stopPropagation();
				 });

				  var cloneCount = 1;
				 $("#add_formula").click(function(e){
			         e.preventDefault();
				 	var clone = $('#detail_formula').clone().attr('id', 'detail_formula'+ cloneCount++).insertAfter($('[id^=detail_formula]:last'));
				 	clone.find(":input:not([readonly='readonly'])").val('');	
				 	clone.find('[type=hidden]').val('');
				 	clone.find('a.icon-minus-sign').attr('onClick','deleteAddress(this);return false');					 	
				 	$('#detail_formula'+(cloneCount-1)).find('.chzn-container').remove();
            		$('#detail_formula'+(cloneCount-1)).find('.chzn-select').removeClass('chzn-done').removeAttr('id').chosen({search_contains: true });
            		
            		$('#detail_formula'+(cloneCount-1)).find('#chzn-selectx1').removeClass('chzn-done').removeAttr('id').chosen({search_contains: true });
				 })

				$(".chzn-select").chosen({search_contains: true });  
				$("#id_sales").chosen({search_contains: true }); 
				$("#id_customer").chosen({search_contains: true });
				$("#id_jns_brg").chosen({search_contains: true });

$("#tgl_jual").datetimepicker({
					changeMonth: true,
				    changeYear: true,
				    showOtherMonths: true,
					dateFormat:'yy-mm-dd',
					timeFormat: 'hh:mm:ss',
			        hourGrid: 8,
			        minuteGrid: 10,		
				});
			});
			
</script>